/*
 Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
 Original sources are available at www.latestbit.com

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 ManagedClient.cpp. Created on: 11.09.2009 12:32:21
 */

#include "smartobjects/network/ManagedClient.hpp"
#include "smartobjects/network/EndpointLocation.hpp"

namespace smartobjects {

ManagedClient::ManagedClient(INetworkFactory* poFactory):
		m_poNetworkFactory(poFactory),
		m_bStarted(false) {
	m_poNetworkFactory->addRef();
}

ManagedClient::~ManagedClient() {
	stop();
	m_poNetworkFactory->release();
	boost::recursive_mutex::scoped_lock oLock(m_mxConnectors);
	m_poEndpointCoordinator->resetManagedConnectionFactory();
}

void ManagedClient::setEndpointLocation(IEndpointLocation* poLocation, IEndpointCoordinator* poCoordinator) {
	boost::recursive_mutex::scoped_lock oLock(m_mxConnectors);
	boost::recursive_mutex::scoped_lock oEndpointLock(m_mxEndpointLocation);
	setNewRefObject(m_poEndpointLocation, poLocation);
	setNewRefObject(m_poEndpointCoordinator, poCoordinator);
	if ( m_poEndpointCoordinator ) {
		m_poEndpointCoordinator->setManagedConnectionFactory(
				this
		);
	}
}

void ManagedClient::start() {
	boost::recursive_mutex::scoped_lock oLock(m_mxConnectors);
	updateConnectors();
	for( ConnectorsMap::iterator it = m_mConnectors.begin(); it!=m_mConnectors.end(); it++ ) {
		it->second->connectAsync();
	}
	m_bStarted= true;
}

void ManagedClient::start(unsigned long nAwaitTimeInSec) {
	boost::recursive_mutex::scoped_lock oLock(m_mxAwaitConnect);
	boost::xtime oXt;
	boost::xtime_get(&oXt, boost::TIME_UTC);
	oXt.sec += nAwaitTimeInSec;
	start();
	if(!m_evAwaitConnect.timed_wait(oLock, oXt)) {
		throw IOException("Timeout occurred when connecting to all specified endpoints!");
	}
}


void ManagedClient::stop() {
	boost::recursive_mutex::scoped_lock oLock(m_mxConnectors);
	m_bStarted = false;
	m_bConnectionStatus = false;
	ConnectorsMap mTempConnectors = m_mConnectors;
	m_mConnectors.clear();
	oLock.unlock();

	for( ConnectorsMap::iterator it = mTempConnectors.begin(); it!=mTempConnectors.end(); it++ ) {
		it->second->close();
		it->second->release();
	}
	mTempConnectors.clear();

	oLock.lock();
	for( Handlers::iterator it = m_aAllHandlers.begin(); it!=m_aAllHandlers.end(); it++ ) {
		if((*it)->getConnection()!=NULL) {
			(*it)->getConnection()->delConnectionListener(*it);
			(*it)->getConnection()->delStreamListener(*it);
		}
		m_poEndpointCoordinator->onRemoved(*it);
		(*it)->release();
	}
	m_aAllHandlers.clear();
}

void ManagedClient::updateConnectors() {
	boost::recursive_mutex::scoped_lock oLock(m_mxConnectors);
	ConnectorsMap mTempConnectors = m_mConnectors;
	m_mConnectors.clear();
	foreach ( URI* poURI, m_poEndpointLocation->getLocations() ) {
		std::string sKey = poURI->getHost() + ":" + boost::lexical_cast<std::string>(poURI->getPort());
		ConnectorsMap::iterator itExistConnector = mTempConnectors.find(sKey);
		if(itExistConnector!=mTempConnectors.end()) {
			m_mConnectors.insert(*itExistConnector);
			mTempConnectors.erase(itExistConnector);
		}
		else {
			IConnector* poConnector = m_poNetworkFactory->createConnector();
			poConnector->setEndpointURI( poURI );
			ConnectionHandler* poHandler =
					new ConnectionHandler(
							poConnector,
							m_poEndpointCoordinator
					);
			m_aAllHandlers.insert(poHandler);

			poConnector->addConnectionListener(poHandler);
			poConnector->addStreamListener(poHandler);

			std::pair<std::string, IConnector*>
				oConnectorPair ( sKey, poConnector );

			m_mConnectors.insert( oConnectorPair );

			if(m_bStarted)
				poConnector->connectAsync();
		}

	}

	for( ConnectorsMap::iterator it = mTempConnectors.begin(); it!=mTempConnectors.end(); it++ ) {
		it->second->close();
		it->second->release();
	}
	mTempConnectors.clear();

}

void ManagedClient::fireOnConnected() {
	SafeForReleaseMethodLock oReleaseLock(this);
	ManagedConnection::fireOnConnected();
	boost::recursive_mutex::scoped_lock oLock(m_mxAwaitConnect);
	m_evAwaitConnect.notify_one();
}

void ManagedClient::fireOnConnectionFailure(ConnectionHandler* poHandler, const std::string& sErrorMessage) {
	SafeForReleaseMethodLock oReleaseLock(this);
	ManagedConnection::fireOnConnectionFailure(poHandler, sErrorMessage);
	restoreConnection(poHandler);
}

void ManagedClient::fireOnDisconnected(ConnectionHandler* poHandler) {
	SafeForReleaseMethodLock oReleaseLock(this);
	ManagedConnection::fireOnDisconnected(poHandler);
	restoreConnection(poHandler);
}

void ManagedClient::restoreConnection(ConnectionHandler* poHandler) {
	if(m_poEndpointCoordinator->onRestoreConnectionNeeded(poHandler)) {
		boost::recursive_mutex::scoped_lock oLock(m_mxConnectors);
		if(!m_bStarted)
			return;
		if(m_aAllHandlers.find(poHandler)!=m_aAllHandlers.end()) {
			IConnection* poConnection = poHandler->getConnection();
			if(poConnection) {
				IConnector* poConnector = dynamic_cast<IConnector*>( poConnection );
				try {
					poConnector->connectAsync();
				}
				catch(const SystemException&){};
			}
		}
	}
}

IManagedConnection* ManagedClient::createManagedConnection() {
	return (ManagedConnection*)this;
}

void ManagedClient::removeManagedConnection(IManagedConnection*) {
	// Nothing to do
}


}
